<template>
  <div class="main">
    <div class="device">
      <div class="dleft" @click="test">
        <span style="font-weight: 500">{{ deviceData.name }}</span>
        <!-- <img style="width: 10vw;" src="@svg/device.svg"/> -->
      </div>
      <div @click="toMain" class="dmid">
        <span style="display: flex"
          ><img
            align="absmiddle"
            style="width: 5vw; margin-right: 5px"
            src="@/assets/svg/id.svg"
          />&nbsp;ID: {{ deviceData.ID }}</span
        >
        <span v-for="item in infoData" :key="item.id" style="display: flex"
          ><img
            align="absmiddle"
            style="width: 5vw; margin-right: 5px"
            src="@/assets/svg/mode.svg"
          /><span
            >&nbsp;{{ item.name }}:
            {{
              item.specs.type === "digital"
                ? item.content === true
                  ? item.specs.high
                  : item.content === false
                  ? item.specs.low
                  : "--"
                : item.content
                ? item.content
                : "--"
            }}{{ item.specs.unit }}</span
          >
        </span>
      </div>
      <div class="dright">
        <div v-for="item in infoData" :key="item.id">
          <van-switch
            v-if="(item.accessMode === 'rw') & (item.specs.type === 'digital')"
            v-model="item.content"
            size="24px"
            :loading="item.load"
            @change="onControlChange(item)"
          />
        </div>
      </div>
    </div>
  </div>
</template>

<script>
//import { Dialog } from 'vant';
import { Toast } from "vant";
import { time } from 'echarts';
export default {
  //name: "Lab-1",
  props: {
    deviceInfo:Object
  },
  components: {},
  activated: function(){
    // console.log("active")
  },
  created: function () {
    this.initInterface();
    this.mqttMsg();
    // let request = indexedDB.open("myDB", 2);

    // //err
    // request.onerror = (event) => {
    //   console.log("数据库打开/创建报错", event);
    // };
    // //如果指定的版本号，大于数据库的实际版本号，就会发生数据库升级事件upgradeneeded。
    // //升级后自动触发success
    // request.onupgradeneeded = (event) => {
    //   let db = event.target.result;
    //   this.db = db;
    //   //建表 名为person,主键为id
    //   let store = db.createObjectStore("deviceCamera", {
    //     keyPath: "id",
    //   });
    //   //新建索引名称、索引所在的属性、配置对象（说明该属性是否允许有重复的值）
    //   store.createIndex("cameraState", "cameraState", {
    //     unique: false,
    //   });
    //   store.createIndex("cameraIP", "cameraIP", {
    //     unique: false,
    //   });
    //   console.log("数据库升级");
    // };
    // // success
    // request.onsuccess = (event) => {
    //   this.db = event.target.result;
    //   console.log("数据库打开/创建成功", event);
    //   //this.getList();
    // };
    // var transaction = this.db.transaction(["deviceCamera"]);
    // let objectStore = transaction.objectStore("deviceCamera");
    // request = objectStore.get(123456);
    // console.log(request);
    // request.onerror = function (e) {
    //   console.log("获取列表失败");
    // };

    // request.onsuccess = function (e) {
    //   if (request.result) {
    //     console.log("cameraState: " + request.result.cameraState);
    //     console.log("cameraIP: " + request.result.cameraIP);
    //   } else {
    //     console.log("未获得数据记录");
    //   }
    // };
  },
  data() {
    return {
      deviceData: {
        ID: this.deviceInfo.id,
        name: this.deviceInfo.devicename,
      },
      timeout: "",
      db: "",
      resData: [],
      iData: [],
      cData: [],
    };
  },
  computed: {
    infoData: function () {
      return this.iData.filter(function (iDatas) {
        return iDatas.view.banner; //返回isShow=true的项，添加到activeUsers数组
      });
    },
    chartData: function () {
      return this.iData.filter(function (iDatas) {
        return iDatas.view.chart; //返回isShow=true的项，添加到activeUsers数组
      });
    },
  },
  methods: {
    test() {
      // 建立读写事务,向对象仓库写入数据记录
      let rrequest = this.db
        .transaction(["deviceCamera"], "readwrite")
        .objectStore("deviceCamera");

      rrequest.add({
        id: 123456,
        cameraState: this.id,
        cameraIP: this.id,
      });
      console.log(rrequest);
      rrequest.onsuccess = (event) => {
        console.log("新增成功");
        this.notify("新增成功");
        this.person = {};
        // 获取数据列表
        //this.getList();
      };

      rrequest.onerror = (event) => {
        console.log("重复数据写入失败");
        this.notify("重复数据写入失败");
      };
    },
    initInterface() {
      this.$http
        .get("http://121.5.58.100:8000/queryDeviceInterface", {
          params: {
            deviceid: this.deviceInfo.id,
          },
          headers: {
            "Content-Type": "application/x-www-form-urlencoded",
          },
        })
        .then((result) => {
          console.log(result.data);
          this.resData = result.data;
          this.iData = [];
          this.cData = [];
          for (let i = 0; i < result.data.length; i++) {
            this.iData.push(result.data[i]);
            if (result.data[i].view.chart) {
              this.cData.push({
                date: [],
                data: [],
              });
            }
          }
          console.log(this.cData);
        });
    },
    formatDate(params) {
      let date = params;
      let formatStr = "HH:mm:ss";
      // 传入日期字符串 - 转成时间戳 - 转成标准时间
      let timeStamp = params.getTime();
      console.log(timeStamp);
      date = new Date(timeStamp);
      formatStr = formatStr.replace(
        new RegExp("yyyy"),
        `${date.getFullYear()}`
      );
      const month = date.getMonth() + 1;
      formatStr = formatStr.replace(
        new RegExp("MM"),
        `${month > 9 ? month : "0" + month}`
      );
      const day = date.getDate();
      formatStr = formatStr.replace(
        new RegExp("dd"),
        `${day > 9 ? day : "0" + day}`
      );
      const hour = date.getHours();
      formatStr = formatStr.replace(
        new RegExp("HH"),
        `${hour > 9 ? hour : "0" + hour}`
      );
      const min = date.getMinutes();
      formatStr = formatStr.replace(
        new RegExp("mm"),
        `${min > 9 ? min : "0" + min}`
      );
      const sec = date.getSeconds();
      formatStr = formatStr.replace(
        new RegExp("ss"),
        `${sec > 9 ? sec : "0" + sec}`
      );
      return formatStr;
    },
    onTimeOut() {
      console.log("timeout")
      Toast("设备不在线或超时，请稍后再试！");
      //this.$parent.updateDevice();
      //this.$forceUpdate()
      this.$router.go(0);
    },
    onControlChange(item) {
      //this.$parent.updateDevice2();
      this.timeout = setTimeout(this.onTimeOut, 5000);
      navigator.vibrate(100);
      console.log(item);
      this.$set(item, "load", true);
      var send = {};
      send[item.identifier] = item.content === true ? "1" : "0";
      console.log(send);
      console.log("sub"+this.deviceInfo.mqttSub)
      this.$mqtt.publish(this.deviceInfo.mqttSub, send);
    },
    toMain() {
      this.$router.push({
        name: "interface_page_index",
        params: {
          resData: this.resData,
          cData: this.cData,
          deviceInfo:this.deviceInfo,
          routerType: "push",
        },
      });
    },
    mqttMsg() {
      // 接收消息处理
      this.$mqtt.message(this.deviceInfo.mqttPub, (topic, message) => {
        console.log(message.toString()); //控制台显示接收到的数据
        this.data = message.toString();
        try {
          this.res = JSON.parse(message.toString());
          for (let i = 0; i < this.chartData.length; i++) {
            var info = this.chartData[i];
            this.cData[i].date.push(this.formatDate(new Date()));
            this.cData[i].data.push(this.res[info.identifier]);
            //this.$forceUpdate();
          }
          console.log(this.cData);
          for (let i = 0; i < this.iData.length; i++) {
            var info = this.iData[i];
            if (info.specs.type === "analog") {
              this.res[info.identifier] = this.res[info.identifier].toFixed(
                info.specs.fixed
              );
            }
            if (info.specs.type === "digital") {
              this.res[info.identifier] =
                this.res[info.identifier] === 1 ? true : false;
            }
            if ((info.accessMode === "rw") & (info.specs.type === "digital")) {
              if (info.load) {
                console.log(info.content,this.res[info.identifier])
                clearInterval(this.timeout)
                //console.log(this.res[info.identifier] === 1 ? true : false);
                if (info.content === this.res[info.identifier]) {
                  Toast.success("设定成功");
                  clearInterval(this.timeout)
                  info.load = false;
                } else {
                  Toast.fail("发生错误");
                  info.load = false;
                }
              } else {
                // this.res[info.identifier] =
                //   this.res[info.identifier] === 1 ? true : false;
                this.$set(info, "content", this.res[info.identifier]);
                console.log("control", this.res[info.identifier]);
              }
            } else if (
              (info.accessMode === "rw") &
              (info.specs.type === "analog")
            ) {
              if (info.load) {
                console.log(info.content,this.res[info.identifier])
                if (info.content == this.res[info.identifier]) {
                  Toast.success("设定成功");
                  clearInterval(this.timeout)
                  info.load = false;
                } else {
                  Toast.fail("发生错误");
                  info.load = false;
                }
              } else {
                this.$set(info, "content", this.res[info.identifier]);
                console.log("set", this.res[info.identifier]);
              }
            } else {
              this.$set(info, "content", this.res[info.identifier]);
            }
            //info.content = this.res[info.identifier];

            //this.$forceUpdate();
            console.log(info);
          }
        } catch (err) {
          console.log(err.message);
        }
      });
    },
  },
};
</script>
<style scoped>
.content {
  padding: 10px 16px;
}
.main {
  margin: auto;
  display: flex;
  flex-direction: row;
  flex-wrap: wrap;
  padding: 10px 20px 10px 20px;
}
.device {
  transition: 0.3s;
  position: relative;
  z-index: 1;
  width: 100vw;
  height: auto;
  display: flex;
  justify-content: left;
  align-items: center;
  border-radius: 20px;
  text-align: left;
  padding: 10px 10px;
  box-shadow: 0px 0px 12px 0 rgb(0 0 0 / 8%);
  background-color: rgba(255, 255, 255, 0.85);
  backdrop-filter: blur(20px) saturate(180%);
}
/* .device:after {
    content: '';
    position: absolute;
    top: 0;
    left: 0;
    right: 0;
    bottom: 0;
    border-radius: 20px;
    -webkit-filter: blur(20px);
    -moz-filter: blur(20px);
    -ms-filter: blur(20px);
    -o-filter: blur(20px);
    filter: blur(20px);
    background-color: rgba(255,255,255,0.8);
    z-index: -1;
} */
.dleft {
  flex: 0 0 20vw;
  width: 50px;
  text-align: center;
  order: -1; /* 让 #left 居于左侧 */
}
.dmid {
  transition: 0.3s;
  width: 100%;
  display: flex;
  flex: 1;
  flex-direction: column;
  margin: 10px;
  font-size: 4vw;
}
.dright {
  flex: 0 0 20vw;
  text-align: center;
}
.custom-button {
  width: auto;
  padding: 5px 10px;
  color: #fff;
  font-size: 4vw;
  line-height: 5vw;
  text-align: center;
  background-color: #0aadee;
  border-radius: 20px;
}
</style>
